package dao

import (
	"crypto/sha1"
	"encoding/hex"
	"go-cloud-disk/common/util"
	"go-cloud-disk/global"
	"time"
)

const (
	// Active 账户正常状态
	Active = iota
	// NotActivicated 未激活
	NotActivicated
	// Baned 被封禁
	Baned
	// OveruseBaned 超额使用被封禁
	OveruseBaned
)

type User struct {
	ID        uint `gorm:"primarykey"`
	CreatedAt time.Time
	UpdatedAt time.Time
	Password  string
}

// 用OpenID获取可登录用户
func GetActiveUserByOpenID(openid string) (User, error) {
	var user User
	result := global.DB.Set("gorm:auto_preload", true).Where("status = ? and open_id = ?", Active, openid).Find(&user)
	return user, result.Error
}

// 用Email获取可登录用户
func GetActiveUserByEmail(email string) (User, error) {
	var user User
	result := global.DB.Set("gorm:auto_preload", true).Where("status = ? and email = ?", Active, email).First(&user)
	return user, result.Error
}

// 用Email获取用户
func GetUserByEmail(email string) (User, error) {
	var user User
	result := global.DB.Set("gorm:auto_preload", true).Where("email = ?", email).First(&user)
	return user, result.Error
}

// 用ID获取用户
func GetUserByID(ID interface{}) (User, error) {
	var user User
	result := global.DB.Set("gorm:auto_preload", true).First(&user, ID)
	return user, result.Error
}

// 用ID获取可登录用户
func GetActiveUserByID(ID interface{}) (User, error) {
	var user User
	result := global.DB.Set("gorm:auto_preload", true).Where("status = ?", Active).First(&user, ID)
	return user, result.Error
}

// 根据给定明文设定 User 的 Password 字段
func (user *User) SetPassword(password string) error {
	//生成16位 Salt
	salt := util.RandStringRunes(16)
	//计算 Salt 和密码组合的SHA1摘要
	hash := sha1.New()
	_, err := hash.Write([]byte(password + salt))
	bs := hex.EncodeToString(hash.Sum(nil))
	if err != nil {
		return err
	}
	//存储 Salt 值和摘要， ":"分割
	user.Password = salt + ":" + bs
	return nil
}

// Update 更新用户
func (user *User) Update(val map[string]interface{}) error {
	return global.DB.Model(user).Updates(val).Error
}
